package cn.jobstart.common.http;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

/**
 * Created by Administrator on 2018/3/21.
 */
public class AuthGet {

    public static <T> T httpGet(String url, Class<T> returnType, int soTimeout, int conTimeout) {
        HttpClient httpClient = HttpRequest.getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, conTimeout);
        httpGet.setParams(params);
        httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
        return execute(httpClient, httpGet, returnType);
    }

    public static <T> T execute(HttpClient httpClient, HttpUriRequest req, Class<T> returnType, String... headers) {

        try {
            // 插入basic验证等基础逻辑
            for (int i = 0; i < headers.length; i += 2) {
                req.addHeader(headers[i], headers[i + 1]);
            }
            HttpResponse jres = httpClient.execute(req);

            HttpEntity ent = jres.getEntity();
            String content = ent != null ? EntityUtils.toString(ent, "UTF-8") : null;
            if (jres.getStatusLine().getStatusCode() >= 200
                    && jres.getStatusLine().getStatusCode() < 300) {
                if (returnType == String.class) {
                    return (T) content;
                }
                return JSON.parseObject(content, returnType);
            } else {
//                log.warn("error response code={}", new Object[]{jres.getStatusLine().getStatusCode()});
            }
        } catch (Exception e) {
//            log.warn("request error,", e);
        }
        return null;
    }

}
